<template>
  <a-modal
    :visible="visible"
    title="上传合同"
    :destroyOnClose="true"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="agreementForm"
      :model="form"
      :rules="rules"
      :label-col="{span: 6}"
      :wrapper-col="{span: 16}"
    >
      <a-form-model-item prop="name" label="合同名称">
        <a-input v-model="form.name" :max-length="20" />
      </a-form-model-item>
      <a-form-model-item prop="beginTime" label="合同有效期">
        <a-range-picker @change="onChangeAgTime">
          <a-icon slot="suffixIcon" type="calendar" />
        </a-range-picker>
      </a-form-model-item>
      <a-form-model-item prop="pictures" label="上传合同">
        <a-upload
          accept=".pdf, .bmp, .jpg, .jpeg, .png, .JPG, .JPEG, .BMP, .PDF, .PNG"
          :multiple="true"
          :action="uploadUrl"
          :headers="headers"
          :beforeUpload="beforeUpload"
          :file-list="fileList"
          @change="handleChange"
          @preview="previewFile"
        >
          <a-button>
            <a-icon type="upload" />上传
          </a-button>
        </a-upload>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { VERSION_NO, APP_KEY, REQUEST_INTEFACE_URL } from '@/common/config'
import md5 from 'md5'
import store from 'store'
import Util from '@/common/util'

const fomrMessage = `必填项不能为空`
const formDefault = function () {
  return {
    name: '', // 合同名称
    beginTime: '', // 合同有效期
    endTime: '', // 合同有效期
    pictures: ''
  }
}

export default {
  name: 'agreement-modal',
  props: {
    visible: Boolean
  },
  data () {
    return {
      optTitle: '',
      form: formDefault(),
      rules: {
        name: [{required: true, message: fomrMessage, trigger: 'blur'}],
        beginTime: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        pictures: [{required: true, message: fomrMessage, trigger: 'blur'}]
      },
      fileList: [],
      headers: {},
      uploadUrl: REQUEST_INTEFACE_URL + '/file/upload'
    }
  },
  methods: {
    beforeUpload (file, fileList) {
      if (fileList.length + this.fileList.length >= 100) {
        this.$message.error('最多上传100个文件！')
        return false
      }
      const uuid = Util.getUUID()
      const headers = {
        appKey: APP_KEY,
        version: VERSION_NO,
        timestamp: (() => new Date().getTime())(),
        nonce: uuid,
        token: store.get('token') ? store.get('token') : '',
        sign: md5(`appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase()
      }
      this.headers = headers
    },
    handleChange ({ file, fileList }) {
      let list = [...fileList]
      list = list.map(v => {
        if (v.response) {
          v.url = v.response.data.url
        }
        return v
      })
      this.fileList = list

      const doneList = list.filter(v => v.url).map(v => v.url)
      this.form.pictures = doneList.length > 0 ? doneList.reduce((pre, current, index, array) => {
        return pre + ',' + current
      }) : ''
    },
    previewFile (file) {
      window.open(file.url, '_blank')
    },
    onChangeAgTime (date, dateStr) {
      this.form.beginTime = dateStr[0]
      this.form.endTime = dateStr[1]
    },
    handleCancel () {
      this.$emit('set-agreement-visible', false)
      this.fileList = []
      this.$refs.agreementForm.resetFields()
    },
    handleOk () {
      this.$refs.agreementForm.validate(valid => {
        if (valid) {
          this.fileList = []
          this.$emit('handle-agreement', this.form)
        }
      })
    }
  },
  watch: {
    visible () {
      this.form = formDefault()
    }
  }

}
</script>
